package com.google.appengine.twitter.security;

import com.google.appengine.twitter.domain.model.User;
import com.google.appengine.twitter.domain.model.UserRepository;
import com.google.inject.Inject;
import com.google.inject.internal.Objects;
import com.google.inject.internal.Preconditions;

public class SimpleAuthenticationManager implements AuthenticationManager {
	
	private UserRepository userRepository;
	private PasswordEncoder passwordEncoder;

	@Inject
	public SimpleAuthenticationManager(UserRepository userRepository, PasswordEncoder passwordEncoder) {
		Preconditions.checkNotNull(userRepository, "userRepository required");
		Preconditions.checkNotNull(passwordEncoder, "passwordEncoder required");
		this.userRepository = userRepository;
		this.passwordEncoder = passwordEncoder;
	}

	@Override
	public AuthenticationResult authenticate(Authentication authentication) {
		
		User user = userRepository.findByEmailOrUsername(authentication.getPrincipal().toString());
		if (user == null) {
			return AuthenticationResult.USER_NOT_FOUND;
		}
		
		String encoded = passwordEncoder.encode(authentication.getCredential().toString());
		if (!Objects.equal(encoded, user.getPassword())) {
			return AuthenticationResult.INCORRECT_CREDENTIAL;
		}
		
		return AuthenticationResult.SUCCESSED;
	}

}
